package com.sywb.chuangyebao.view.fragment;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.contract.BusinessTVContract;
import com.sywb.chuangyebao.library.player.AliPlayerView;
import com.sywb.chuangyebao.library.player.IVideoController;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;
import com.sywb.chuangyebao.utils.ScreenSwitchUtils;
import com.sywb.chuangyebao.utils.WindowUtil;

import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;

/**
 * 主页-创TV
 */
public class BusinessTVFragment extends BaseStatisticsFragment<BusinessTVContract.Presenter> implements BusinessTVContract.View {

    public FrameLayout llContainer;
    public LinearLayout llBusinesstvProgram;
    public TextView tvBusinesstvProgram;
    public LinearLayout llBusinesstvHistory;
    public TextView tvBusinesstvHistory;
    public View tabCursor;
    public ViewPager viewPager;

    private int fragmentWhereTab;
    private boolean isVisibleToTab = true;// 当前Fragemnt所在的Tab页是否可见
    private boolean isVisibleToUser = false;// 当前Fragemnt是否对用户可见

    private AliPlayerView rlVideo;

    private ScreenSwitchUtils instance;
    private boolean isFullScreen;//是否处于全屏状态

    private String liveURL = null;

    /**
     * Fragment 实例
     */
    public static BusinessTVFragment newInstance(Object... pramars) {
        BusinessTVFragment fragment = new BusinessTVFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_businesstv;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);
        if (bundle != null) {
            fragmentWhereTab = bundle.getInt("p0", 0);
        } else {
            fragmentWhereTab = getArguments().getInt("p0", 0);
        }

        llContainer = getView(R.id.ll_container);
        llBusinesstvProgram = getView(R.id.ll_businesstv_program);
        tvBusinesstvProgram = getView(R.id.tv_businesstv_program);
        llBusinesstvHistory = getView(R.id.ll_businesstv_history);
        tvBusinesstvHistory = getView(R.id.tv_businesstv_history);
        tabCursor = getView(R.id.tab_cursor);
        viewPager = getView(R.id.view_pager);

        llBusinesstvProgram.setOnClickListener(this);
        llBusinesstvHistory.setOnClickListener(this);

        llContainer.removeAllViews();

        ViewGroup.LayoutParams layoutParams = llContainer.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = (int) (org.bining.footstone.utils.ScreenUtils.getScreenWidth() * 0.56F);
        llContainer.setLayoutParams(layoutParams);

        instance = ScreenSwitchUtils.init(mActivity.getApplicationContext());

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPresenter.changeView(position, tvBusinesstvProgram, tvBusinesstvHistory);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        if (rlVideo != null) {
            rlVideo.destroy();
        }

        rlVideo = new AliPlayerView(mActivity);
        rlVideo.setOnPlayerListener(new OnPlayerListener() {
            @Override
            public void onInit() {
            }

            @Override
            public void onPrepared() {
            }

            @Override
            public void onStarted() {
                if (isVisibleToTab && isVisibleToUser) {
                    instance.start(mActivity);
                } else {
                    mPresenter.cancelCountDownTimer();
                    rlVideo.autoPause();
                    instance.stop();
                }
            }

            @Override
            public void onPaused() {
                instance.stop();
            }

            @Override
            public void onCompletion() {
                instance.stop();
            }

            @Override
            public void onError(int causeCode, int sceneCode, String message) {
                instance.stop();
            }

            @Override
            public void onShare(int platformType) {
            }

            @Override
            public void onClickScreenDirection() {
                instance.toggleScreen();
                // advance(VideoFullScreenActivity.class, liveURL);
            }

            @Override
            public void showToolsView() {
            }

            @Override
            public void hideToolsView() {
            }

            @Override
            public void updateProgress(int curPosition, int bufferPosition, int duration) {
            }
        });

        addPlayerView();
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", fragmentWhereTab);
        super.onSaveInstanceState(outState);
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.MAINTABCHANGE)})
    public void rxMainTabChange(String data) {
        Logger.e("rxMainTabChange：" + data);
        if (Integer.parseInt(data) == 0) {
            if (!isVisibleToTab) {
                isVisibleToTab = true;
                if (isVisibleToUser) {
                    mPresenter.onStartLoadMore();
                    rlVideo.autoResume();
                }
            }
        } else {
            if (isVisibleToTab) {
                isVisibleToTab = false;
                mPresenter.cancelCountDownTimer();
                rlVideo.autoPause();
                instance.stop();
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (!isCanClick(view)) return;
        switch (view.getId()) {
            case R.id.ll_businesstv_program:
                mPresenter.changeView(0, tvBusinesstvProgram, tvBusinesstvHistory);
                break;
            case R.id.ll_businesstv_history:
                mPresenter.changeView(1, tvBusinesstvProgram, tvBusinesstvHistory);
                break;
        }
    }

    public void addPlayerView() {
        isFullScreen = false;
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        llContainer.addView(rlVideo, params);
    }

    public void removePlayerView() {
        isFullScreen = true;
        llContainer.removeView(rlVideo);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (!isVisibleToTab || !isVisibleToUser) {
            return;
        }
        RxBus.get().post(Constants.ISFULLSCREEN, String.valueOf(newConfig.orientation));
        boolean orientation = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;//屏幕方向是否为横屏
        Logger.e("屏幕方向改变！！！是否为横屏：" + orientation);
        rlVideo.onConfigurationChanged(newConfig);
        if (orientation) {// 横屏
            if (mActivity == null) return;
            Activity activity = WindowUtil.scanForActivity(mActivity);
            if (activity == null) return;
            WindowUtil.hideSystemBar(mActivity);
            if (isFullScreen) return;
            removePlayerView();
            ViewGroup contentView = activity.findViewById(android.R.id.content);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            contentView.addView(rlVideo, params);
        } else {// 竖屏
            if (mActivity == null) return;
            Activity activity = WindowUtil.scanForActivity(mActivity);
            if (activity == null) return;
            if (!isFullScreen) return;
            WindowUtil.showSystemBar(mActivity);
            ViewGroup contentView = activity.findViewById(android.R.id.content);
            contentView.removeView(rlVideo);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            addPlayerView();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Logger.e("setUserVisibleHint：" + isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (rlVideo != null) {
            if (rlVideo.getPlayerState() == IAliyunVodPlayer.PlayerState.Idle) {
                Logger.e("rlVideo Idle");
                if (isVisibleToUser && isVisibleToTab) {
                    Logger.e("rlVideo start");
                    mPresenter.onStartLoadMore();
                    if (liveURL != null) {
                        rlVideo.start();
                    }
                }
            } else {
                Logger.e("rlVideo Other");
                if (isVisibleToUser && isVisibleToTab) {
                    Logger.e("rlVideo autoResume");
                    mPresenter.onStartLoadMore();
                    rlVideo.autoResume();
                } else {
                    Logger.e("rlVideo autoPause");
                    mPresenter.cancelCountDownTimer();
                    rlVideo.autoPause();
                    instance.stop();
                }
            }
        } else {
            Logger.e("rlVideo 为空");
        }
    }

    @Override
    public void onStart() {
        Logger.e("onStart");
        super.onStart();
    }

    @Override
    public void onResume() {
        Logger.e("onResume");
        if (isVisibleToUser && isVisibleToTab) {
            mPresenter.onStartLoadMore();
            rlVideo.autoResume();
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        mPresenter.cancelCountDownTimer();
        rlVideo.autoPause();
        instance.stop();
        super.onPause();
    }

    @Override
    public void onStop() {
        Logger.e("onStop");
        super.onStop();
    }

    @Override
    public void onDestroy() {
        Logger.e("onDestroy");
        rlVideo.destroy();
        super.onDestroy();
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    @Override
    public void startLive(String liveUrl) {
        this.liveURL = liveUrl;
        // liveUrl = "rtmp://live.hkstv.hk.lxdns.com/live/hks";
        rlVideo.init(mActivity, IVideoController.MODE_LIVE, liveUrl, null, "00:00");
        rlVideo.start();
    }

    @Override
    public ViewPager getViewPager() {
        return viewPager;
    }

    @Override
    public View getTabCursor() {
        return tabCursor;
    }

}
